import db, { IsDBInit } from "../database/ExampleDB";
import {
  IErrorData,
  IResponseData,
  ResponseErrorOrUndefined
} from "@/model/frame/ResponseModel";
import { LoginResponse } from "@/model/ResponseModel";
import JWTTool from "@/utils/frame/JWTTool";
import { RolePermissionTable } from "@/model/RBAC/RolePermissionTable";
import { PermissionTool } from "@/utils/frame/PermissionTool";
import { RecordState } from "@/model/frame/IRecordState";
import CryptTool from "@/utils/frame/CryptTool";
import {
  MethodType,
  RouteMiddleWare,
  Router
} from "../yssoa/middleware/Router";
import { User } from "@/model/RBAC/User";
import { ITokenPayload } from "@/utils/SystemTool";

const _loggerName = "Mock/User";

class MockFunction {
  public static login: RouteMiddleWare = async (ctx, next) => {
    const _resd: IResponseData<LoginResponse | ResponseErrorOrUndefined> = {
      code: 200,
      data: undefined
    };
    const _user = db.user!.$.by("username", ctx.req.body.username);
    if (_user && !_user.isDelete) {
      if (_user.password === ctx.req.body.password) {
        // 提取权限信息
        // 根据 user 找到 Role
        // 根据 Role 找打 Permission
        // 提取所有的 Permission
        const _userRoles = db.userRoleTable!.$.find({
          userID: { $eq: _user.id }
        });
        const _rolePermissions: RolePermissionTable[] = [];
        _userRoles.forEach(item => {
          _rolePermissions.push(
            ...db.rolePromiseTable!.$.find({ roleID: { $eq: item.roleID } })
          );
        });

        const _data: LoginResponse = {
          token: JWTTool.getToken<ITokenPayload>(
            {
              id: _user.id,
              username: _user.username,
              permissions: _rolePermissions.map<string>(item => {
                const _permission = db.permission!.$.by("id", item.promiseID);
                return _permission ? _permission.code : "";
              })
            },
            { expiresIn: "1h" }
          )
        };
        _resd.data = _data;
      } else {
        _resd.data = { error: "LoginError", message: "用户名或密码错误" };
        _resd.code = 400;
      }
    } else {
      _resd.data = {
        error: "UserNotFound",
        message: "用户已被禁用，请联系管理员。"
      };
      _resd.code = 403; // 故障码后面定义
    }

    ctx.res.response = _resd;
    return next();
  };

  public static getList: RouteMiddleWare = async (ctx, next) => {
    const _rspd: IResponseData = { code: 200, data: {} };

    // 这里是浏览器访问因此权限已经在 Store 里了可以直接使用工具访问权限
    if (PermissionTool.hasPermission("RBAC:User:List")) {
      _rspd.data = { users: db.user!.$.find() };
    } else {
      _rspd.code = 403;
      const _error: IErrorData = {
        error: "PermissionError",
        message: "没有数据权限!"
      };
      _rspd.data = _error;
    }

    console.log("[Mock/GetList]:", _rspd);
    ctx.res.response = _rspd;

    return next();
  };

  public static create: RouteMiddleWare = async (ctx, next) => {
    const _resd: IResponseData<User | ResponseErrorOrUndefined> = {
      code: 200,
      data: undefined
    };

    // 这里是浏览器访问因此权限已经在 Store 里了可以直接使用工具访问权限
    if (PermissionTool.hasPermission("RBAC:User:Create")) {
      const _user = db.user!.$.insert({
        ...new RecordState(CryptTool.uuid()),
        username: ctx.req.body.username,
        password: ctx.req.body.password
      });
      if (_user) {
        _resd.data = _user;
      } else {
        _resd.code = 400;
        const _error: IErrorData = {
          error: "ParamError",
          message: "用户名重复,或其他错误"
        };
        _resd.data = _error;
      }
    } else {
      _resd.code = 403;
      const _error: IErrorData = {
        error: "Forbidden",
        message: "无创建权限!"
      };
      _resd.data = _error;
    }
    ctx.res.response = _resd;

    return next();
  };

  public static update: RouteMiddleWare = async (ctx, next) => {
    const _resd: IResponseData<User | ResponseErrorOrUndefined> = {
      code: 200,
      data: undefined
    };

    // 这里是浏览器访问因此权限已经在 Store 里了可以直接使用工具访问权限
    if (PermissionTool.hasPermission("RBAC:User:Update")) {
      const _user = db.user!.$.update({
        ...ctx.req.body
      });
      _resd.data = _user;
    } else {
      _resd.code = 403;
      const _error: IErrorData = {
        error: "PermissionError",
        message: "没有数据权限!"
      };
      _resd.data = _error;
    }
    ctx.res.response = _resd;

    return next();
  };
}

// 这里可以编写后端的逻辑
Router.instance().addRoute({
  regx: /\/api\/v0\/Login/,
  method: MethodType.POST,
  middleware: MockFunction.login
});

Router.instance().addRoute({
  regx: /\/api\/v0\/User/,
  method: MethodType.GET,
  middleware: MockFunction.getList
});

Router.instance().addRoute({
  regx: /\/api\/v0\/User/,
  method: MethodType.PUT,
  middleware: MockFunction.update
});
Router.instance().addRoute({
  regx: /\/api\/v0\/User/,
  method: MethodType.POST,
  middleware: MockFunction.create
});
